"""
投资决策相关的Pydantic模型定义
"""

from datetime import datetime
from typing import List, Optional, Dict, Any, Literal
from pydantic import BaseModel, Field


class InvestmentSignal(BaseModel):
    """投资信号模型"""
    signal: Literal["buy", "sell", "hold"] = Field(..., description="投资信号")
    confidence: float = Field(..., ge=0, le=1, description="信号置信度")
    strength: Literal["strong", "moderate", "weak"] = Field(..., description="信号强度")
    reasoning: str = Field(..., description="信号推理")
    risk_level: Literal["low", "medium", "high"] = Field(..., description="风险等级")
    time_horizon: Literal["short", "medium", "long"] = Field(..., description="投资时间框架")
    expected_return: Optional[float] = Field(None, description="预期收益率")
    max_loss: Optional[float] = Field(None, description="最大损失")


class PortfolioDecision(BaseModel):
    """投资组合决策模型"""
    ticker: str = Field(..., description="股票代码")
    action: Literal["buy", "sell", "hold", "reduce", "increase"] = Field(..., description="投资行动")
    quantity: int = Field(..., description="交易数量")
    target_price: Optional[float] = Field(None, description="目标价格")
    stop_loss: Optional[float] = Field(None, description="止损价格")
    take_profit: Optional[float] = Field(None, description="止盈价格")
    position_size_pct: float = Field(..., ge=0, le=1, description="仓位占比")
    max_position_size: int = Field(..., description="最大持仓数量")
    current_price: Optional[float] = Field(None, description="当前价格")
    expected_return: Optional[float] = Field(None, description="预期收益率")
    risk_score: float = Field(..., ge=0, le=1, description="风险评分")
    confidence: float = Field(..., ge=0, le=1, description="决策置信度")
    reasoning: str = Field(..., description="决策推理")
    time_horizon: str = Field(..., description="投资时间框架")
    entry_criteria: List[str] = Field(default_factory=list, description="入场条件")
    exit_criteria: List[str] = Field(default_factory=list, description="出场条件")


class TradingAction(BaseModel):
    """交易行动模型"""
    action_id: str = Field(..., description="行动ID")
    ticker: str = Field(..., description="股票代码")
    action_type: Literal["buy", "sell", "hold"] = Field(..., description="行动类型")
    quantity: int = Field(..., description="交易数量")
    price: Optional[float] = Field(None, description="交易价格")
    order_type: Literal["market", "limit", "stop"] = Field("market", description="订单类型")
    priority: Literal["high", "medium", "low"] = Field("medium", description="优先级")
    execution_time: Optional[datetime] = Field(None, description="执行时间")
    status: Literal["pending", "executed", "cancelled", "failed"] = Field("pending", description="状态")
    reasoning: str = Field(..., description="交易推理")
    risk_parameters: Dict[str, float] = Field(default_factory=dict, description="风险参数")
    expected_outcome: Dict[str, float] = Field(default_factory=dict, description="预期结果")


class PortfolioState(BaseModel):
    """投资组合状态模型"""
    total_value: float = Field(..., description="总价值")
    cash_balance: float = Field(..., description="现金余额")
    invested_amount: float = Field(..., description="已投资金额")
    positions: Dict[str, Dict[str, Any]] = Field(default_factory=dict, description="持仓信息")
    daily_return: Optional[float] = Field(None, description="日收益率")
    total_return: Optional[float] = Field(None, description="总收益率")
    max_drawdown: Optional[float] = Field(None, description="最大回撤")
    sharpe_ratio: Optional[float] = Field(None, description="夏普比率")
    volatility: Optional[float] = Field(None, description="波动率")
    beta: Optional[float] = Field(None, description="Beta系数")
    last_updated: datetime = Field(default_factory=datetime.now, description="最后更新时间")


class InvestmentRecommendation(BaseModel):
    """投资建议模型"""
    ticker: str = Field(..., description="股票代码")
    recommendation: Literal["strong_buy", "buy", "hold", "sell", "strong_sell"] = Field(..., description="投资建议")
    target_price: Optional[float] = Field(None, description="目标价格")
    current_price: Optional[float] = Field(None, description="当前价格")
    upside_potential: Optional[float] = Field(None, description="上涨潜力")
    downside_risk: Optional[float] = Field(None, description="下跌风险")
    confidence_level: float = Field(..., ge=0, le=1, description="置信水平")
    time_horizon: str = Field(..., description="投资时间框架")
    key_catalysts: List[str] = Field(default_factory=list, description="关键催化剂")
    risk_factors: List[str] = Field(default_factory=list, description="风险因素")
    analyst_summary: str = Field(..., description="分析师总结")
    supporting_analysis: Dict[str, Any] = Field(default_factory=dict, description="支持分析")
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")


class PerformanceMetrics(BaseModel):
    """绩效指标模型"""
    period: str = Field(..., description="统计周期")
    total_return: float = Field(..., description="总收益率")
    annualized_return: Optional[float] = Field(None, description="年化收益率")
    volatility: float = Field(..., description="波动率")
    sharpe_ratio: Optional[float] = Field(None, description="夏普比率")
    max_drawdown: float = Field(..., description="最大回撤")
    win_rate: Optional[float] = Field(None, description="胜率")
    profit_factor: Optional[float] = Field(None, description="盈利因子")
    calmar_ratio: Optional[float] = Field(None, description="卡玛比率")
    sortino_ratio: Optional[float] = Field(None, description="索提诺比率")
    beta: Optional[float] = Field(None, description="Beta系数")
    alpha: Optional[float] = Field(None, description="Alpha系数")
    information_ratio: Optional[float] = Field(None, description="信息比率")
    tracking_error: Optional[float] = Field(None, description="跟踪误差")


class BacktestResult(BaseModel):
    """回测结果模型"""
    strategy_name: str = Field(..., description="策略名称")
    start_date: datetime = Field(..., description="开始日期")
    end_date: datetime = Field(..., description="结束日期")
    initial_capital: float = Field(..., description="初始资金")
    final_value: float = Field(..., description="最终价值")
    total_trades: int = Field(..., description="总交易次数")
    winning_trades: int = Field(..., description="盈利交易次数")
    losing_trades: int = Field(..., description="亏损交易次数")
    performance_metrics: PerformanceMetrics = Field(..., description="绩效指标")
    trade_history: List[Dict[str, Any]] = Field(default_factory=list, description="交易历史")
    equity_curve: List[Dict[str, float]] = Field(default_factory=list, description="权益曲线")
    drawdown_periods: List[Dict[str, Any]] = Field(default_factory=list, description="回撤期间")
    monthly_returns: Dict[str, float] = Field(default_factory=dict, description="月度收益")
    risk_metrics: Dict[str, float] = Field(default_factory=dict, description="风险指标")


class DecisionAuditLog(BaseModel):
    """决策审计日志模型"""
    decision_id: str = Field(..., description="决策ID")
    timestamp: datetime = Field(default_factory=datetime.now, description="时间戳")
    ticker: str = Field(..., description="股票代码")
    decision_type: str = Field(..., description="决策类型")
    input_data: Dict[str, Any] = Field(..., description="输入数据")
    analysis_results: Dict[str, Any] = Field(..., description="分析结果")
    final_decision: Dict[str, Any] = Field(..., description="最终决策")
    confidence_scores: Dict[str, float] = Field(..., description="置信度分数")
    risk_assessment: Dict[str, Any] = Field(..., description="风险评估")
    execution_status: str = Field(..., description="执行状态")
    actual_outcome: Optional[Dict[str, Any]] = Field(None, description="实际结果")
    performance_impact: Optional[float] = Field(None, description="绩效影响")
    lessons_learned: Optional[str] = Field(None, description="经验教训")


class AlertRule(BaseModel):
    """预警规则模型"""
    rule_id: str = Field(..., description="规则ID")
    rule_name: str = Field(..., description="规则名称")
    ticker: Optional[str] = Field(None, description="股票代码")
    condition: str = Field(..., description="触发条件")
    threshold: float = Field(..., description="阈值")
    alert_type: Literal["price", "volume", "technical", "fundamental", "news"] = Field(..., description="预警类型")
    severity: Literal["low", "medium", "high", "critical"] = Field(..., description="严重程度")
    is_active: bool = Field(True, description="是否激活")
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    last_triggered: Optional[datetime] = Field(None, description="最后触发时间")
    trigger_count: int = Field(0, description="触发次数")


class Alert(BaseModel):
    """预警消息模型"""
    alert_id: str = Field(..., description="预警ID")
    rule_id: str = Field(..., description="规则ID")
    ticker: str = Field(..., description="股票代码")
    message: str = Field(..., description="预警消息")
    severity: Literal["low", "medium", "high", "critical"] = Field(..., description="严重程度")
    triggered_at: datetime = Field(default_factory=datetime.now, description="触发时间")
    current_value: float = Field(..., description="当前值")
    threshold_value: float = Field(..., description="阈值")
    is_acknowledged: bool = Field(False, description="是否已确认")
    acknowledged_at: Optional[datetime] = Field(None, description="确认时间")
    action_taken: Optional[str] = Field(None, description="采取的行动")
